import React, { useState, useEffect } from 'react';
import './Orbit.scss';

const Orbit: React.FC<any> = (props) => {
    const {tabItems} = props;
    const [currentIndex, setCurrentIndex] = useState(0);
    const [rotationStep, setRotationStep] = useState(0);
    const [isRotating, setIsRotating] = useState(false);

    // 椭圆轨迹的7个位置（相对于圆心的坐标）
    // 7个div均分280度空间，从-140度到+140度（以正下方为0度，顺时针为正）
    // 椭圆参数：水平半径=180，垂直半径=120
    const angles = [-88, -63, -37, 0, 37, 63, 88]; // 度数

    // 当数据超过7条时，在正上方增加重叠位置
    const topOverlapPositions = [
        { x: 0, y: -240, }, // 正上方第一层
        { x: -20, y: -260, }, // 正上方第二层，稍微偏左
        { x: 20, y: -260, }, // 正上方第三层，稍微偏右
        { x: -40, y: -280, }, // 正上方第四层
        { x: 40, y: -280, }, // 正上方第五层
    ];
    const positions = angles.map((angle, index) => {
        const radian = (angle * Math.PI) / 180; // 正确的角度转弧度公式
        if (index === 0) {
            return {
                x: Math.round(180 * Math.sin(radian)) * 3 + 206, // 水平半径 180
                y: Math.round(120 * Math.cos(radian)) * 2, // 垂直半径 120
            };
        }
        if (index === 1) {
            return {
                x: Math.round(180 * Math.sin(radian)) * 3 - 12, // 水平半径 180
                y: Math.round(120 * Math.cos(radian)) * 2 + 14, // 垂直半径 120
            };
        }
        if (index === 2) {
            return {
                x: Math.round(180 * Math.sin(radian)) * 3 + 24, // 水平半径 180
                y: Math.round(120 * Math.cos(radian)) * 2 + 20, // 垂直半径 120
            };
        }
        if (index === 3) {
            return {
                x: Math.round(180 * Math.sin(radian)) * 3, // 水平半径 180
                y: Math.round(120 * Math.cos(radian)) * 2, // 垂直半径 120
            };
        }
        if (index === 4) {
            return {
                x: Math.round(180 * Math.sin(radian)) * 3, // 水平半径 180
                y: Math.round(120 * Math.cos(radian)) * 2 + 20, // 垂直半径 120
            };
        }
        if (index === 5) {
            return {
                x: Math.round(180 * Math.sin(radian)) * 3 + 22, // 水平半径 180
                y: Math.round(120 * Math.cos(radian)) * 2 + 24, // 垂直半径 120
            };
        }
        if (index === 6) {
            return {
                x: Math.round(180 * Math.sin(radian)) * 3 - 164, // 水平半径 180
                y: Math.round(120 * Math.cos(radian)) * 2, // 垂直半径 120
            };
        }
        return {
            x: Math.round(180 * Math.sin(radian)) * 3, // 水平半径 180
            y: Math.round(120 * Math.cos(radian)) * 2, // 垂直半径 120
        };
    });

    useEffect(() => {
        // 每6秒转动一次
        const interval = setInterval(() => {
            setIsRotating(true);
            setRotationStep((prev) => prev + 1);
            setCurrentIndex((prev) => (prev + 1) % tabItems.length); // 使用实际数据长度

            // 500ms后设置为停止状态
            setTimeout(() => {
                setIsRotating(false);
            }, 500);
        }, 6000);

        return () => clearInterval(interval);
    }, [tabItems.length]);

    // 计算每个div当前应该在的位置
    const getItemPosition = (itemIndex: number) => {
        const totalItems = tabItems.length;
        if (totalItems <= 7) {
            // 原有逻辑：7个或更少的项目
            const positionIndex = (itemIndex + rotationStep) % 7;
            return { ...positions[positionIndex], opacity: 1 };
        } else {
            // 新逻辑：超过7个项目时
            const adjustedIndex = (itemIndex + rotationStep) % totalItems;
            if (adjustedIndex < 7) {
                // 前7个位置使用椭圆轨迹
                return { ...positions[adjustedIndex], opacity: 1 };
            } else {
                // 超出的项目放在正上方重叠位置
                const overlapIndex = (adjustedIndex - 7) % topOverlapPositions.length;
                return topOverlapPositions[overlapIndex];
            }
        }
    };

    // 判断是否在顶部位置（-120度或120度）
    const isTopPosition = (itemIndex: number) => {
        const totalItems = tabItems.length;
        if (totalItems <= 7) {
            const positionIndex = (itemIndex + rotationStep) % 7;
            // 顶部两个位置：索引0(-120度)和索引6(120度)
            return positionIndex === 0;
        } else {
            const adjustedIndex = (itemIndex + rotationStep) % totalItems;
            return adjustedIndex === 0 || adjustedIndex >= 7;
        }
    };

    // 判断哪个div当前在0度位置（正下方）
    const getActiveIndex = () => {
        // 找到当前在0度位置的div索引
        const zeroPositionIndex = 3; // angles数组中0度对应的索引
        const totalItems = tabItems.length;
        if (totalItems <= 7) {
            // 计算当前哪个div在这个位置
            return (zeroPositionIndex - (rotationStep % 7) + 7) % 7;
        } else {
            // 超过7个项目时，计算当前在0度位置的项目
            return (zeroPositionIndex - (rotationStep % totalItems) + totalItems) % totalItems;
        }
    };

    // 获取当前在0度位置的div对应的内容索引
    const getBottomContentIndex = () => {
        return getActiveIndex();
    };

    return (
        <>
            <div className="orbit-container">
                {/* 椭圆轨迹容器 */}
                <div className="orbit-wrapper">
                    <div className="orbit">
                        {tabItems.map((item: any, index: number) => {
                            const position = getItemPosition(index);
                            const isActive = getActiveIndex() === index;
                            const isTop = isTopPosition(index);
                            const totalItems = tabItems.length;
                            const adjustedIndex = (index + rotationStep) % totalItems;
                            const isOverlap = totalItems > 7 && adjustedIndex >= 7;

                            return (
                                <div
                                    key={index}
                                    className={`orbit-item item-${index + 1} ${isActive ? 'active' : ''} ${isTop && isRotating ? 'top-fade-out' : ''} ${isTop && !isRotating ? 'top-fade-in' : ''} ${isOverlap ? 'overlap-item' : ''}`}
                                    style={{
                                        transform: `translate(${position.x}px, ${position.y}px) ${isActive ? 'scale(1.2)' : 'scale(1)'}`,
                                        opacity: 1,
                                        zIndex: isOverlap ? 1 : 2,
                                    }}
                                >
                                    <div className="title">{item.projectTypeName}</div>
                                    <img className="center-bottom" src={require("@/assets/img/center-bottom.png")} alt="" />
                                </div>
                            );
                        })}
                    </div>
                </div>
            </div>
            <div className="tab-title">
                <img src={require("@/assets/img/title-right.png")} alt="" />
                <div className="title">{tabItems[getBottomContentIndex()].projectTypeName}</div>
                <img src={require("@/assets/img/title-left.png")} alt="" />
            </div>
            <div className="tab-content">
                {
                    tabItems[getBottomContentIndex()].attribute &&
                    // 使用 activeIndex 作为 key，确保切换 tab 时重新渲染内容
                    <div className="contents" key={currentIndex}>
                        {tabItems[getBottomContentIndex()].attribute.map((item: any, ind: number) => (
                            <div key={ind} className={currentIndex === 3 ? "content-item item-right-10" : "content-item"}>
                                <div className="sub-title">
                                    <span>{item.projectFieldName}
                                        <div className={`danwei l${item.projectFieldUnit.length}`}>（{item.projectFieldUnit}）</div>
                                    </span>

                                </div>
                                <div className="sub-state">
                                    {item.projectFieldValue}
                                </div>
                            </div>
                        ))}
                    </div>
                }
            </div>
        </>
    );
};

export default Orbit;